import win32gui
from typing import Dict, List
from ..log.logging import log_message

class WindowInfo:
    def __init__(self , hwnd : int):
        # 获取窗口句柄
        self.hwnd : int = hwnd
        # 获取窗口名称
        self.title : str = win32gui.GetWindowText(hwnd)
        # 获取窗口位置
        self.position : tuple = win32gui.GetWindowRect(hwnd)
        # 获取窗口大小
        self.size : tuple = (self.position[2] - self.position[0], self.position[3] - self.position[1])
        # 获取窗口是否可见  
        self.is_visible : bool = win32gui.IsWindowVisible(hwnd)
        # 获取窗口是否启用
        self.is_enabled : bool = win32gui.IsWindowEnabled(hwnd)
        # 获取窗口是否被最小化
        self.is_minimized : bool = win32gui.IsIconic(hwnd)
        # 是否为主窗口
        self.is_main : bool = False

    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            "hwnd": self.hwnd,
            "title": self.title,
            "position": self.position,
            "size": self.size,
            "is_visible": self.is_visible,
            "is_enabled": self.is_enabled,
            "is_minimized": self.is_minimized,
            "is_main": self.is_main,
        }

class WindowManager:
    """窗口管理器"""
    # 游戏窗口类名
    GAME_CLASS_NAME = "MainWnd class of ArkEngine"

    # 窗口信息
    WINDOW_INFO = {}

    # 窗口位置
    WINDOW_POSITIONS = {
        (0, 0),         #窗口一
        (1200, 100),    #窗口二
        (0,700),        #窗口三
    }

    # 窗口大小
    WINDOW_SIZE = (1200, 700)

    def __init__(self, hwnd=None):
        """初始化窗口管理器"""
        self.hwnd = hwnd
        self.windows : Dict[int, dict] = {}
        pass
    
    # 查找游戏窗口
    def find_game_window(self) -> List[int]:
        """查找游戏窗口"""
        try:
            hwnd_list = []
            hwnds = win32gui.FindWindowEx(0, 0, self.GAME_CLASS_NAME, None)
            while hwnds:
                hwnd_list.append(hwnds)
                hwnds = win32gui.FindWindowEx(0, hwnds, self.GAME_CLASS_NAME, None)
            return hwnd_list    
        
        except Exception as e:
            log_message(f"查找游戏窗口失败: {e}", "error")
            return []
        
    def get_window(self) -> List[WindowInfo]:
        """获取窗口列表"""
        try:
            return [WindowInfo(hwnd) for hwnd in self.find_game_window()]
            pass
        except Exception as e:
            log_message(f"获取窗口列表失败: {e}", "error")
            return []

    def find_window(self, hwnd: None) -> WindowInfo:
        """查找窗口"""
        return WindowInfo(hwnd)
    
    def get_text(self, window: WindowInfo, position: tuple) -> str:
        """获取窗口文本"""
        return window.get_text(position)
    
    def get_child_window(self, window: WindowInfo, position: tuple) -> WindowInfo:
        """获取子窗口"""
        return window.get_child_window(position)


